package com.jmda.platform.commom;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

@Component("SpringContextUtil")
public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    //applicationContext 注入
    public void setApplicationContext(ApplicationContext arg) throws BeansException {
        // TODO Auto-generated method stub
        SpringContextUtil.applicationContext = arg;
    }

    //根据类名获得一个对象
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        try {
            return (T) applicationContext.getBean(beanName);
        } catch (Exception e) {
            return null;
        }
    }

    //根据类名获得一个对象
    public static <T> T getBean(Class<T> type) {
        try {
            return applicationContext.getBean(type);
        } catch (Exception e) {
            return null;
        }
    }
	/**
	 * 根据提供的bean名称得到对应于指定类型的服务类
	 * 
	 * @param servName
	 *            bean名称
	 * @param clazz
	 *            返回的bean类型,若类型不匹配,将抛出异常
	 */
	public static <T> T getBean(String beanId, Class<T> clazz) {

		return applicationContext.getBean(beanId, clazz);
	}
    //找到在applicationContext里声明的,所有FreeMarkerConfig和其子类的bean
    public static FreeMarkerConfig getFreeMarkerConfig() {
        return BeanFactoryUtils.beanOfTypeIncludingAncestors(applicationContext, FreeMarkerConfig.class, true, false);
    }
}
